package com.mazha.rabbitmq.controller;

import com.alibaba.fastjson.JSON;
import com.mazha.rabbitmq.base.MqMessage;
import com.mazha.rabbitmq.common.constant.MqConstant;
import com.mazha.rabbitmq.common.cache.ChatGlobalCache;
import com.mazha.rabbitmq.enums.ErrorCodeEnum;
import com.mazha.rabbitmq.pojo.dto.ChatGroupDTO;
import com.mazha.rabbitmq.pojo.vo.ChatMessageVO;
import com.mazha.rabbitmq.pojo.vo.UserChatParamVO;
import com.mazha.rabbitmq.pojo.vo.UserRegisterVO;
import com.mazha.rabbitmq.result.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 聊天会话
 *
 * @author leizi
 * @date 2023/12/09
 */
@RestController
@RequestMapping("/chat")
@Slf4j
public class ChatSpeakController {

    private final RabbitTemplate rabbitTemplate;

    public ChatSpeakController(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 初始创建聊天室
     * 两人建立会话与多人建立会话连接都以创建群为基础
     *
     * @param userChatParamVO 会话消息
     * @return
     */
    @PostMapping("/room")
    public RestResult createChatRoom(@Validated @RequestBody UserChatParamVO userChatParamVO) {
        log.info("create chatRoom param:{}", JSON.toJSONString(userChatParamVO));
        ConcurrentHashMap<Long, UserRegisterVO> userRegisterCacheMap = ChatGlobalCache.userRegisterCacheMap;
        // 校验用户
        if (!userRegisterCacheMap.containsKey(userChatParamVO.getInitiateUserId())) {
            return RestResult.failResult(ErrorCodeEnum.USER_INITIATE_NOT_EXISTS);
        }
        List<Long> userIdList = userChatParamVO.getReceiveUserList();
        userIdList.add(userChatParamVO.getInitiateUserId());
        // 初始化群名称
        String initGroupName = userIdList.stream().map(userRegisterCacheMap::get).map(userRegisterVO -> userRegisterVO.getName()).collect(Collectors.joining(","));
        ChatGroupDTO chatGroupDTO = new ChatGroupDTO();
        chatGroupDTO.setGroupId(UUID.randomUUID().toString());
        chatGroupDTO.setGroupName(initGroupName);
        chatGroupDTO.setUserIdList(userIdList);
        ChatGlobalCache.chatGroupCache.put(chatGroupDTO.getGroupId(), chatGroupDTO);
        log.info("create chatRoom group:{}", JSON.toJSONString(chatGroupDTO));
        return RestResult.successResult(chatGroupDTO);
    }

    /**
     * 发送聊天消息
     *
     * @param chatMessageVO 消息详情
     * @return
     */
    @PostMapping("/speak")
    public RestResult chatSpeak(@Validated @RequestBody ChatMessageVO chatMessageVO) {
        log.info("chat speak param:{}", JSON.toJSONString(chatMessageVO));
        ConcurrentHashMap<String, ChatGroupDTO> chatGroupCache = ChatGlobalCache.chatGroupCache;
        // 校验群组
        if (!chatGroupCache.containsKey(chatMessageVO.getGroupId())) {
            return RestResult.failResult(ErrorCodeEnum.GROUP_NOT_EXISTS);
        }
        MqMessage mqMessage = new MqMessage(chatMessageVO);
        rabbitTemplate.convertAndSend(MqConstant.SPEAK_EXCHANGE, MqConstant.SPEAK_ROUTING_KEY, mqMessage);
        return RestResult.successResult();
    }

    // TODO 修改群名称

}
